package com.itheima.utils;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MapperUtil {
    private static InputStream resourceAsStream;
    private static SqlSessionFactory sqlSessionFactory;
    private static SqlSession sqlSession;


    public static SqlSession getSqlSession() throws IOException {
        // 读取 数据库连接相关 核心配置文件
        resourceAsStream = Resources.getResourceAsStream("sqlConfig.xml");
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }

    public static <T> T getMapper(Class<T> tClass) throws IOException {
        SqlSession sqlSession = getSqlSession();
        T mapper = sqlSession.getMapper(tClass);

        return (T) Proxy.newProxyInstance(
                mapper.getClass().getClassLoader(),
                mapper.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object obj = null;
                        obj = method.invoke(mapper,args);
                        close();
                        return obj;
                    }
                });
    }

    public static void close() {
        if (sqlSession != null) {
            sqlSession.commit();
            sqlSession.close();
        }
    }

}
